package com.ruoyi.livesass.api.sync;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;

import cn.hutool.core.util.StrUtil;

@Component
public class SysConfigUtils implements ApplicationRunner{
	
    @Autowired
    private ISysConfigService configService;
    
	private Map<String, Long> subNameDeptidMap = Maps.newHashMap();
	
	private Map<Long, String> deptidSubNameMap = Maps.newHashMap();
	
	private Map<Long, String> ywidMap = Maps.newHashMap();

	
	@Override
	public void run(ApplicationArguments args) throws Exception {
		subNameDeptidMap = Maps.newHashMap();
		deptidSubNameMap = Maps.newHashMap();
		ywidMap = Maps.newHashMap();
	}
	
	
	public String getSubUserName(long zbjid) {
		try {
			syncLoadSysConfig();
			if(deptidSubNameMap.containsKey(zbjid)) {
				return deptidSubNameMap.get(zbjid);
			}
			return null;
		}catch(Exception e) {
			return null;
		}
		
	}
	
	public Long getZbjid(String sunUserName){
		try {
			syncLoadSysConfig();
			if(subNameDeptidMap.containsKey(sunUserName)) {
				return subNameDeptidMap.get(sunUserName);
			}
			return null;
		}catch(Exception e) {
			return null;
		}
	}
	
	public String getYwid(long zbjid) {
		try {
			syncLoadSysConfig();
			if(ywidMap.containsKey(zbjid)) {
				return ywidMap.get(zbjid);
			}
			return null;
		}catch(Exception e) {
			return null;
		}
	}
	
	
	private void syncLoadSysConfig() throws Exception {
		SysConfig sysConfig = configService.selectConfigByKey2("sys_config");
		if (null != sysConfig && !StrUtil.isBlankIfStr(sysConfig.getRemark())) {
			JSONObject sysConfigJsonObject = JSONObject.parseObject(sysConfig.getRemark());
			if (sysConfigJsonObject.containsKey("activityConfig")) {
				JSONArray activityConfigList = sysConfigJsonObject.getJSONArray("activityConfig");
				for (int i = 0; i < activityConfigList.size(); i++) {
					JSONObject item = activityConfigList.getJSONObject(i);
					deptidSubNameMap.put(item.getLong("zbjid"), item.getString("subusername"));
					subNameDeptidMap.put(item.getString("subusername"), item.getLong("zbjid"));
					if(item.containsKey("ywid")) {
						ywidMap.put(item.getLong("zbjid"), item.getString("ywid"));
					}
				}
			}
		}
	}


	

}
